<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      html {
        /* 滚动行为： 丝滑*/
        scroll-behavior: smooth;
      }
      #backTop {
        position: fixed;
        right: 20px;
        bottom: 60px;
      }

      div {
        font-size: 100px;
        text-align: center;
        width: 800px;
        height: 400px;
        line-height: 400px;
        margin: 10px auto;
        background-color: #4a9478;
      }

      .hide {
        display: none;
      }
    </style>
  </head>
  <body>
    <div>A</div>
    <div>B</div>
    <div>C</div>
    <div>D</div>
    <div>E</div>
    <button id="backTop" class="hide">回到顶部</button>
    <script>
      //当点击按钮时，页面的scrollTop为0；
      var btn = document.getElementById('backTop');

      btn.addEventListener('click', function () {
        document.documentElement.scrollTop = document.body.scrollTop = 0;
        console.log('haha');
      });
      document.addEventListener('scroll', function () {
        var scrollTop =
          document.documentElement.scrollTop || document.body.scrollTop;
        console.log('scroll');
        if (scrollTop >= 100) {
        btn.classList.remove('hide');
      } else {
        btn.classList.add('hide');
      }
      });
      
    </script>
  </body>
</html>
